﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rosetta.Default.AddIns.RegularExpressions
{
    public sealed class RegexConverter : Converter
    {
        #region Constructors

        public RegexConverter()
            : base ("Regex Converter")
        {
            Category = "RegularExpressions";

            Add<string, Regex>("Create", Create, "pattern");
            Add<string, Regex>("CreateCompiled", CreateCompiled, "pattern");
            Add<Regex, string, IEnumerable<Match>>("GetMatches", GetMatches, "regex", "input");
            Add<Match, string>("GetValue", GetValue, "match");
            Add<Regex, string, bool>("IsMatch", IsMatch, "regex", "input");
        }

        #endregion

        #region Class Methods

        private static Regex Create([NotNull] string pattern)
        {
            if (string.IsNullOrEmpty(pattern))
            {
                throw new ArgumentNullException("pattern");
            }

            return new Regex(pattern);
        }

        private static Regex CreateCompiled([NotNull] string pattern)
        {
            if (string.IsNullOrEmpty(pattern))
            {
                throw new ArgumentNullException("pattern");
            }

            return new Regex(pattern, RegexOptions.Compiled);
        }

        private static IEnumerable<Match> GetMatches([NotNull] Regex regex, [NotNull] string input)
        {
            if (regex == null)
            {
                throw new ArgumentNullException("regex");
            }
            if (string.IsNullOrEmpty(input))
            {
                throw new ArgumentNullException("input");
            }

            return regex.Matches(input).Cast<Match>();
        }

        private static string GetValue([NotNull] Match match)
        {
            if (match == null)
            {
                throw new ArgumentNullException("match");
            }

            return match.Value;
        }

        private static bool IsMatch([NotNull] Regex regex, [NotNull] string input)
        {
            if (regex == null)
            {
                throw new ArgumentNullException("regex");
            }
            if (string.IsNullOrEmpty(input))
            {
                throw new ArgumentNullException("input");
            }

            return regex.IsMatch(input);
        }

        #endregion
    }
}